//
//  LWOAthus.swift
//  ios8-01 weibo框架搭建
//
//  Created by blue on 16/2/28.
//  Copyright © 2016年 honeywell. All rights reserved.
//

import UIKit

import SVProgressHUD

class LWOAthus: UIViewController,UIWebViewDelegate {
    
    //网页视图
    var  webView :UIWebView = UIWebView()
    
    //appkey
    let  client_id = "2557454927"
    //授权回调地址
    let  redirect_uri = "https://www.baidu.com"
    //设置视图
    override func loadView() {
        
        //设置
        //webView = UIWebView()
        super.loadView()
        
        self.view = webView
        print("加载授权登陆界面")
        
        webView.delegate = self
        //设置导航栏
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "closeWebView")
        
    }
    
    //加载授权界面
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        self.setupWebView()
    }
    
    func   setupWebView(){
        
        let  string = "https://api.weibo.com/oauth2/authorize?client_id=2557454927&redirect_uri=http://www.baidu.com"
        
        let  url = NSURL(string: string)!
        
        let request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)
        
    }
    
    //关闭授权登陆界面
    func  closeWebView(){
        
        dismissViewControllerAnimated(true, completion: nil )
        
    }
    
    //MARK  网页视图的代理方法
    
    //
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //后去授权码－－－发送给微博服务器－－－获取令盘－－－
        print("响应：\(request)")
         let  URL = request.URL?.absoluteString
        print("完整的URL:\(URL)")
        
        //1.如果不是回调的地址则继续进行加载
        if  ((URL?.hasPrefix("http://www.baidu.com")) == nil){
            
            return  true
        }
        //2.如果是回调地址则截取授权码--先判断是否包含授权码、
        let  look = request.URL?.query
        print("查看回调地址：\(look)")
        let  codeStr = "code="
        
        
        if  ((look?.hasPrefix(codeStr)) != nil){
            
            let   code = (look! as  NSString).substringFromIndex((codeStr as  NSString).length)
            //得到了授权码==把授权码发送给微博服务器
            print("得到了授权码: \(code)")
            
            
            self.sendTokenToWeiboServer(code, accessTokenFinished: { (response, error) -> () in
                
                //判断一下如果没错则授权成功
                if  error != nil{
                    
                    print("授权失败")
                }else{
                    
                    print("授权成功")
                }
                
                
            })
            
        }else{
            
            //取消授权
            self.closeWebView()
        }
        
        
        
        return  true
    }
    
    
    //MARK: - 获得令牌
    func  sendTokenToWeiboServer(code: String , accessTokenFinished : (response:[String : AnyObject?], error : NSError?) ->() ){
            
            //1.请求地址
            let URLString = "https://api.weibo.com/oauth2/access_token"
            //2.请求参数
            let parameters = [
                "client_id"  :  "2557454927",
                "client_secret"  :  "4b5a49e474e2bb0cb71f1d6537090d7f",
                "grant_type" :  "authorization_code",
                "code"  :  code,
                "redirect_uri"  :     "http://www.baidu.com"
            ]
            /*
            LWNetworkTools.sharedNetworkTools().POST(URLString, parameters: parameters, success: { (_ , response) -> Void in
                
                print("请求令牌成功，令牌是：\(response)")//把令牌拿出去＝＝闭包
                
                //把返回结果转成字典
                let  dict = response as? [String : AnyObject]
                
                accessTokenFinished(response: dict! , error: nil)
                
                }) { (_, error) -> Void in
                    
                    print("请求令牌失败，错误原因是：\(error)")//请求失败的原因也拿出去＝＝闭包
                    accessTokenFinished(response : nil , error:error)
            }*/
        }

        
    }
    func webViewDidStartLoad(webView: UIWebView) {
        
//          SVProgressHUD.showInfoWithStatus("正在拼命的加载!!!!")
        SVProgressHUD.showWithStatus("正在拼命的加载!!!!", maskType: SVProgressHUDMaskType.Black)
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
        SVProgressHUD.showErrorWithStatus("加载失败", maskType: SVProgressHUDMaskType.Black)
        
    }
    


   
